<template>
  <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
    :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">
    <template v-if="!designState">
      <!-- <Signature v-model:value="field.options.defaultValue" ref="SignImg" :lineWidth='3' :config="field.options" :isDefault='0' @confrim="saveData" /> -->
      <div class="comments-list">
        <div v-for="(item, index) in commentList" :key="index" class="comments-item">
          <div :class="field.options.isEditProcess ? 'comments-item-left' : 'comments-item-left-all'" v-html="item.contentTemp"></div>
          <!-- 在流程监控可删除 -->
          <el-icon v-if="field.options.isEditProcess" @click="handleDelateRow(item, index)" class="ml10 cursor"><Delete /></el-icon>
        </div>
      </div>
    </template>
    <!-- <template v-if="field.options.readonly">
      <span class="readonly-mode-field">{{ field.options.defaultValue.toString() }}</span>
    </template> -->
  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import i18n, { translate } from "@/utils/i18n";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";
import { generateId } from "@/utils/util";
import Signature from "@/components/ZHLX-Components/ZHLX-signature/index.vue"

export default {
  name: "process-comments-widget",
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },

  },
  components: {
    FormItemWrapper,
    Signature,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],
      widgetKey: '',
    }
  },
  watch: {
    'field.options.timeType' : {
      deep: true,
      handler() {
        this.setData();
      }
    },
  },
  computed: {
    allowDefaultFirstOption() {
      return !!this.field.options.filterable || !!this.field.options.remote
    },

    remoteMethod() {
      if (!!this.field.options.remote && !!this.field.options.onRemoteQuery) {
        return this.remoteQuery
      } else {
        return undefined
      }
    },

    selectKey() {
      return this.widgetKey || this.field.id
    },

    commentList() {
      if (this.field.options.defaultValue) {
        return this.setData()
      }
    },
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    this.registerToRefList()
    this.initOptionItems()
    this.initFieldModel()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()
  },

  mounted() {
    this.handleOnMounted()
    this.setData()
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {
    /**
     * 获取选中项label
     * @return {*}
     */
    getSelectedLabel() {
      return this.$refs.fieldEditor.selectedLabel
    },

    refreshWidgetKey() {  //强制刷新组件！！
      this.widgetKey = 'select-key-' + generateId()
    },
    saveData(val) {
      if (!val || !val.length) return
    },
    /**
     * 处理数据
     */
    setData() {
      if (Array.isArray(this.field.options.defaultValue) && this.field.options.defaultValue.length) {
        let commentList = this.field.options.defaultValue.filter(item => typeof item !== 'string').map(item => {
          item.contentTemp = ''
          item.handleTime && (item.time = this.processTime(Number(item.handleTime)))
          const templateData = {
            'default': this.generateTemplate(item, 'default'),
            'template1': this.generateTemplate(item, 'template1'),
            'template2': this.generateTemplate(item, 'template2')
          };
          item.contentTemp = templateData[this.field.options.template]
          return item
        })
        return this.handleSort(commentList)
      }
    },
    // 删除数据
    handleDelateRow(delateItem, index) {
      this.field.options.defaultValue = this.field.options.defaultValue.filter((item) => item.handleTime !== delateItem.handleTime)
      this.syncUpdateFormModel(this.field.options.defaultValue);
      this.dispatch('VFormRender', 'fieldValidation', [this.getPropName()])
    },
    /**
     * 生成模板
     * @param item 模板项对象
     * @param templateType 模板类型
     * @returns 生成的模板字符串
     */
    generateTemplate(item, templateType) {
      const handleOpinion = item.handleOpinion ? `<span class="m6">${item.handleOpinion}</span>` : '';
      const userName = item.userName ? `<span class="m6">${item.userName}</span>` : '';
      const time = item.time || '';
      switch (templateType) {
        case 'default':
          return `<div>${handleOpinion}${userName}${time}</div>`;
        case 'template1':
          return `
            ${handleOpinion}
            <div class="align-right">
              ${userName}${time}
            </div>
          `;
        case 'template2':
          return `
            ${handleOpinion}
            ${item.userName ? `<div class="align-right">${item.userName}</div>` : ''}
            ${item.time ? `<div class="align-right">${item.time}</div>` : ''}
          `;
        default:
          return '';
      }
    },
    /**
     * 处理时间格式
     * @param {*} n 
     */
    processTime(n) {
      const timeType = this.field.options.timeType || 'YYYY-MM-DD HH:mm:ss'
      const now = new Date(n)
      const y = timeType.includes('YYYY') ? now.getFullYear() : ''
      const m = timeType.includes('MM') ? now.getMonth() + 1 : ''
      const d = timeType.includes('DD') ? now.getDate() : ''
      const s = timeType.includes('HH:mm:ss') ? ' ' + now.toTimeString().substr(0, 8) : ''
      const mm = m ? "-" + (m < 10 ? "0" + m : m) : ''
      const dd = d ? "-" + (d < 10 ? "0" + d : d) + '' : ''
      let date = y + mm + dd
      let time = s
      if (timeType.includes('ZH')) {
        date = y + '年' + (timeType.includes('MM') ? m + '月' : '') + (timeType.includes('DD') ? d + '日' : '')
        time = s.replace(/(\d{2}):(\d{2}):(\d{2})/, '$1时$2分$3秒')
      }
      return date + time
    },
    /**
     * 排序
     */
    handleSort(commentList) {
      const sortType = this.field.options.sortType
      if (this.field.options.sort && sortType) {
         commentList = commentList.sort((a, b) => {
          return this.field.options.sort == 'asc' ? a[sortType] - b[sortType] : b[sortType] - a[sortType]
        })
      }
      return commentList
    },

  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/global.scss";
/* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}
.comments-item {
  width: 100%;
  padding-left: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .comments-item-left-all {
    width: calc(100% - 10px);
  }
  .comments-item-left {
    width: calc(100% - 40px);
  }
  .cursor {
    cursor: pointer;
  }
  &:last-of-type {
    margin-bottom: 0;
  }
  :deep(.align-right) {
    text-align: right;
  }
  :deep(.m6) {
    margin-right: 6px;
  }
  .ml10 {
    margin-left: 10px;
  }
}
</style>